<?php

/**
 * Description of msgtype_model
 *
 * @author terminus
 */
class Msgtype_model extends CI_Model {

    private $tableName = 'msgtype';

    public function __construct() {
        parent::__construct();
    }

    public function getMsgtype($msgtype, $is_by_id = 1) {
        if (1 == $is_by_id) {
            $where['id'] = $msgtype;
        } else {
            $where['type_name'] = $msgtype;
        }

        $result = $this->db->get_where($this->tableName, $where);
        if ($result->num_rows() > 0) {
            return $result->row();
        }
        return FALSE;
    }

    public function getMsgtypes($only_count = 0, $is_for_reply = 0, $limit = '', $offset = '') {
        if (1 != $only_count) {
            if ($limit > 0) {
                $this->db->limit($limit);
                if ($offset > 0) {
                    $this->db->limit($limit, $offset);
                }
            }
            if (1 === $is_for_reply || 0 === $is_for_reply) {
                $this->db->where(array('for_reply' => $is_for_reply));
            }
        }

        $result = $this->db->order_by('id', 'DESC')->get($this->tableName);
        if ($result->num_rows() > 0) {
            if (1 == $only_count) {
                return $result->num_rows();
            }
            return $result->result();
        }
        return FALSE;
    }

    public function addMsgtype($type_name, $desc, $for_reply = 0) {
        if ($this->getMsgtype($type_name, 0)) {
            return FALSE;
        }

        $set = array(
            'type_name' => $type_name,
            'description' => $desc,
            'for_reply' => $for_reply
        );

        $this->db->insert($this->tableName, $set);
        $id = $this->db->insert_id();
        if ($id > 0) {
            return $id;
        }
        return FALSE;
    }

    public function editMsgtype($id, $type_name, $desc, $for_reply) {
        $where['id'] = $id;
        $set = array(
            'type_name' => $type_name,
            'description' => $desc,
            'for_reply' => $for_reply
        );

        if (TRUE === $this->db->update($this->tableName, $set, $where, 1)) {
            return TRUE;
        }
        return FALSE;
    }

    public function delMsgtype($msgtype, $is_by_id = 1) {
        if (1 == $is_by_id) {
            $where['id'] = $msgtype;
        } else {
            $where['type_name'] = $msgtype;
        }

        $this->db->delete($this->tableName, $where, 1);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        }
        return FALSE;
    }

}
